﻿using AutoMapper;
using B.S.Production.Domain.Entities;
using B.S.Production.ErrorCode;
using B.S.Production.Write.API.Application.Command.MaterialsRequiredCommand;
using B.S.Production.Write.API.Application.Command.ProductionOrderCommand;
using MediatR;
using SqlSugar;
using Yitter.IdGenerator;

namespace B.S.Production.Write.API.Application.CommandHandlers.MaterialsRequiredCommandHandler
{
    public class AddMaterialsRequiredCommandHandler : IRequestHandler<AddMaterialsRequiredCommand, ApiResult<int>>
    {
        private readonly ISqlSugarClient db;
        private readonly IMapper mapper;

        public AddMaterialsRequiredCommandHandler(ISqlSugarClient db, IMapper mapper)
        {
            this.db = db;
            this.mapper = mapper;
        }

        public async Task<ApiResult<int>> Handle(AddMaterialsRequiredCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();         
            var entity = mapper.Map<List<MaterialsRequired>>(request.Materials);
            foreach (var item in entity)
            {
                item.ProductNumber  = YitIdHelper.NextId();
                result.Data=  await db.Insertable(item).ExecuteCommandAsync();
            }
            
            //result.Data = await db.Insertable(entity).ExecuteCommandAsync();
            if (result.Data > 0)
            {
                result.Code = ApiEnums.添加成功;
                result.Msg = ApiEnums.添加成功.ToString();
            }
            else
            {
                result.Code = ApiEnums.添加失败;
                result.Msg = ApiEnums.添加失败.ToString();
            }
            return result;
        }
    }
}
